# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

# max entry when running on google appengine.
# this is due to performance issue.
COUNT_X_GAE = 10

from oauth2 import Client, Consumer, Token

try:
    from urlparse import parse_qs, parse_qsl
except ImportError:
    from cgi import parse_qs, parse_qsl
    
def user():     
    return dict(form=auth())    

    
@auth.requires_login()
def index():
    
    response.flash = "Welcome my twitter desktop!"
    return dict(message='')
          
def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()

def __add_link__(text):

    l=text.split()

    ret=''
    try:
        for i, w in enumerate(l):
            if w.startswith('http') or w.startswith('https'):
                l[i]=A(w, _href=w, _target='_blank').xml()
            elif w.startswith('@'):
                l[i]=A(w, _href='http://twitter.com/%s' %w.replace('@', ''), _target='_blank').xml()
            elif w.startswith('#'):
                l[i]=A(w, _href='http://twitter.com/#!/search?q=%s' %w.replace('#', ''), _target='_blank').xml()

            ret+=l[i] + ' '
    except UnicodeDecodeError:
        logger.error('Error enconding tweet message')
        return text
    
    return ret

import docclass
# get the last 20 home status twitts and highlight the favorite

def __classified_post__(status, category=None):

    cl = docclass.fisherclassifier(docclass.getwords, db, cache.ram)
    cl.setminimum('favorite', 0.60)
           
    items = []
        
    for s in status:

        item = s.user.screen_name
        item += ' '
        item += s.text
        
        # classify the post with a ml technique
        # item_cat,rate = cl.classify(item)
        item_cat,rate = cache.ram('%s' %s.id, lambda: cl.classify(item), time_expire=cache_time) # cache for 1 hour
                                                      
        if (category != None and category == item_cat) or category == None:
               
            items.append(
                DIV(
                    DIV(
                        IMG(_src='%s' %s.user.profile_image_url, _width='48px', _height='48px' ,_style='margin: 0'), 
                        _id='left', _style='display: table-cell'
                       ) ,
                    DIV(                    
                        P(                        
                            SPAN('%s ' %s.user.name, _style='font-weight: bold' ),
                            SPAN('%s ' %s.user.screen_name, _style='display:none', _id='screen_name'),
                            XML(__add_link__('@%s (%.2f)' %(s.user.screen_name, (rate if category else 0 )))), 
                            A(IMG(_src=URL('static/images','spam.png'), _width='15px', _height='15px'),_href='#' , _onclick="spam( '%s')" %s.id, _title='spam'),                   
                            BR(),
                            SPAN(
                                XML(__add_link__(s.text)), _id='text') , _style='vertical-align: top'),
                        _style='display: table-cell; vertical-align: top; padding-left: 6px', _id='right'
                
                        ) , _id='%s' %s.id, _style='display: table-row'
                   )            
            )
              
    return items
    
    
@auth.requires_login()
def fav_tweets():

    import datetime
    
    start = datetime.datetime.now()

    tapi = _get_api()
    
    if request.env.web2py_runtime_gae:
        status = tapi.GetHomeStatus(count=COUNT_X_GAE)
    else:
      status = tapi.GetHomeStatus()
      
    session.since_id = status[0].id
    
    stop = datetime.datetime.now()
    
    logger.debug('Got twitts %d home timeline in %d sec' %(len(status), (stop-start).seconds))
    
    start = datetime.datetime.now()   
            
    items = __classified_post__(status, 'favorite')
    
    stop = datetime.datetime.now()
    
    logger.debug('%d twitts classified in %d sec' %(len(items), (stop-start).seconds))
    
    return DIV(items, _id='container', _style='display: table; width:100%' ).xml()
    
    
@auth.requires_login()
def spam():
              
    tapi = _get_api()
    
    # classifier
    cl = docclass.fisherclassifier(docclass.getwords, db)
                          
    # classify the post with a ml technique            
    # get the spam twitt                  
    
    cl.train(request.vars.text, 'spam')
      
    # put the item in the cache too:
    cache.ram('%s' %request.vars.id, None)
    cache.ram('%s' %request.vars.id, lambda: ['spam', 1.0] , time_expire=cache_time) # cache for 1 hour
                  
    return 'ok'


def refresh():

    tapi = _get_api()
    
    logger.debug(session.since_id)
    
    status = tapi.GetHomeStatus(since_id=session.since_id)
           
    if status and len(status) > 0:
        session.since_id = status[0].id
    else:
        return None     
    
    items = __classified_post__(status, 'favorite')
            
    if items and len(items) > 0:         
        return DIV(items, _id='container', _style='display: table; border-bottom:#C0C0C0 1px solid;  width:100%' ).xml()


def check_new():

    tapi = _get_api()
    
    logger.debug(session.since_id)
    
    if request.env.web2py_runtime_gae:
        status = tapi.GetHomeStatus(since_id=session.since_id, count=COUNT_X_GAE)
    else:
      status = tapi.GetHomeStatus(since_id=session.since_id)
    
    
    
    if status and len(status) > 0:    
        items = __classified_post__(status, 'favorite')
               
        if items and len(items) > 0:
            logger.debug('%d new post(s)' %len(items))
            return len(items)
        
    return 0

def tag_cloud():

    res = db(db.fc.category == 'favorite').select(orderby=~db.fc.count, limitby=(0, 15))
               
    _list=[LI(A(r.feature, _href='https://twitter.com/#!/search/%s%s' %('%23', r.feature), _target='_blank')) for r in res]
    
    return DIV(BR(), H6(T('Favorite Tag')) ,UL(_list, _id='tag_cloud')).xml()


def post_form():

    return dict()
